// pages/inoculationUnit/inoculationUnit.js
const util = require('../../utils/util.js')
import * as utils from '../../utils/util.js'
import request from '../../utils/http.js'
var qqSDK = require('../../scripts/qqmap-wx-jssdk.min.js');

//获取当前经纬度信息
// 实例化API核心类
var qqMap = new qqSDK({
  key: 'EPYBZ-EPD3D-QDU42-HOJJE-BMN3V-4SBB3'    // 必填
});
Page({
  // 页面的初始数据
  data: {
    keyWord: '',
    activeName: '1',
    changeArea: false,//地址选择框弹出
    areaList: {},//省市区列表
    userArea: "",
    areaids: [],//选中地址
    vaccineStationList: [],//接种单位列表
    latitude: '',
    longitude: '',  
    searchKeyword: '',
    isFromSearch: true,   // 用于判断数组是不是空数组，默认true，空的数组  
    searchPageNum: 1,   // 设置加载的第几次，默认是第一次  
    callbackcount: 20,      //返回数据的个数  
    searchLoading: false, //"上拉加载"的变量，默认false，隐藏  
    searchLoadingComplete: true,  //“没有数据”的变量，默认false，隐藏 
    haveAndnoneData:true,//当前地址下没有数据
    windowHeight:'',
    page: 1,
    size:40,
    flag: true,
    searchTitle:''
  },
  //获取地区列表
  getArea() {
    utils.HttpRequst(true, "/baby-cloud-base/area/selectAreaListByH5","post",{},(res)=>{
      if (res.data.code == 200) {
        this.setData({
          areaList: res.data.data
        })
      }
    })
  },
  //打开选择地址弹窗
  changeArea() { 
    //选择地址弹窗处理
    this.setData({
      changeArea: true
    })
  },
  //关闭选择地区弹窗
  onClose() {
    this.setData({
      changeArea: false
    })
  }, 
  //切换地址
  complateSelArea(e) {
    let arealist = e.detail;
    let str = arealist.values[1].name;
    let areaId = arealist.values[1].code;
    wx.setStorageSync('userArea', str)
    wx.setStorageSync('areaId', areaId)
    this.setData({
      userArea: str,
      areaId: areaId,
      vaccineStationList: [],
      searchTitle:'',
      searchKeyword: ''
    })
    var data={
      areaId:areaId
    }
    //处理完成关闭弹窗
    this.onClose();
    this.reLoad(data);
  },
  //关闭选接种地区
  cancel() {
    //处理完成关闭弹窗
    this.onClose();
  },
  //获取接种单位列表
  reLoad(data) {
    let that = this;
    let { page } = data;
    if (page == undefined){
      Object.assign(data, { page: 1})
      that.setData({
        page: 1
      })
    }
    utils.HttpRequst(false, "/baby-cloud-base/mobileVaccineStation/list","post",{
      size:40,
      ...data
      },(res)=>{
      if (res.data.code == 200) {
        let a = res.data.data
        let _listData = Object.values(a.reduce((re, item) => {
          re[item.receiveTime] ? re[item.receiveTime].push(item) : re[item.receiveTime] = [item];
          return re;
        }, {}));
        this.setData({
          vaccineStationList: that.data.vaccineStationList.concat(_listData)
        })
        let len = _listData.length == 0? 0 : _listData[0].length;
        if (0 < len && len < 40){
          //数据加载完了
          this.setData({
            flag: false,
            searchLoading: true,
            searchLoadingComplete:false,
            haveAndnoneData:true
          })
        } else if (len == 40){
          this.setData({
            flag: true,
            searchLoading: false,
            searchLoadingComplete: true,
            haveAndnoneData: true
          })
        } else if (len == 0){
          //当前地址下没有数据
          that.setData({ 
            flag: false,
            searchLoading: true,
            searchLoadingComplete: true,
            haveAndnoneData: false
          })
        }
      }
    })
  },
  loadMore() {
    let flag = this.data.flag;
    if (flag) {
      this.setData({
        flag: false,//加载数据开关关闭
        searchLoading: false,  //显示加载中.... 
        searchLoadingComplete: true, //把“没有数据”设为true，隐藏  
        haveAndnoneData:true
      })
      var data = {
        areaId: this.data.areaId,
        page: ++this.data.page
      }
      this.reLoad(data);
    }
  },
  //输入框事件，每输入一个字符，就会触发一次  
  bindKeywordInput(e) {
    this.setData({
      searchTitle:e.detail.value
    })
  },

  //点击搜索按钮，触发事件  
  keywordSearch(e) {
    this.setData({    
      searchPageNum: 1,   //第一次加载，设置1  
      vaccineStationList:[],  //放置返回数据的数组,设为空  
      isFromSearch: true,  //第一次加载，设置true  
      searchLoading: true,  //把"上拉加载"的变量设为true，显示  
      searchLoadingComplete:true, //把“没有数据”设为true，隐藏  
    })
    var data={
      title: this.data.searchTitle,
      areaId: this.data.areaId,
    }
    this.reLoad(data);
  },
  keyboardSearch(e){
    this.setData({
      searchPageNum: 1,   //第一次加载，设置1  
      vaccineStationList: [],  //放置返回数据的数组,设为空  
      isFromSearch: true,  //第一次加载，设置true  
      searchLoading: true,  //把"上拉加载"的变量设为true，显示  
      searchLoadingComplete: true, //把“没有数据”设为true，隐藏  
    })
    var data = {
      title: e.detail.value,
      areaId: this.data.areaId,
    }
    this.reLoad(data);
  },
  onAreaChange(event) {
    this.setData({
      activeNames: event.detail
    });
  },
  onLoad: function (options) {
    this.getArea();//获取地址列表
    let that = this;
    var searchH = 0;
    //创建节点选择器
    let query = wx.createSelectorQuery();
    //选择id
    query.select('.unitSearch').boundingClientRect()
    query.exec(function (res) {
      //res就是 所有标签为mjltest的元素的信息 的数组
      //取高度
      wx.getSystemInfo({
        success: function (e) {
          let h = e.windowHeight;
          let sh = h - res[0].height;
          that.setData({
            windowHeight: sh
          })
        }
      });
    })
  },
  onShow(){
    wx.showLoading({
      title: '定位中...',
      icon:'none'
    })
    let that = this;
      /**获取当前坐标 */
      wx.getLocation({
        // type: 'gcj02', 
        isHighAccuracy: true,
        success: (res) => {
          wx.hideLoading()
          var latitude = res.latitude //纬度
          var longitude = res.longitude //经度
          let userArea = wx.getStorageSync('userArea') || '';
          let areaId = wx.getStorageSync('areaId') || '';
          if (userArea && userArea!=''){
            qqMap.reverseGeocoder({
              location:{
                latitude,
                longitude
              },
              success(res){
                console.log(res)
              },
            })
            that.setData({
              userArea,
              areaId,
              latitude,
              longitude
            });
            console.log(this.data.areaId)
            this.reLoad({ areaId});//获取接种单位列表
          }else{
            qqMap.reverseGeocoder({
              location: {
                latitude,
                longitude
              },
              success: (res) => {
                console.log(res)
                var address = res.result.address_component.city;
                let str = res.result.ad_info.city_code;
                var addressId = '';
                addressId = str.substring(3);
                that.setData({
                  latitude: latitude,
                  longitude: longitude,
                  userArea: address,
                  areaId: addressId
                });
                let data = {
                  areaId: addressId
                }
                this.reLoad(data);//获取接种单位列表
              }
            })
          }
        },
        fail(err){
          wx.hideLoading()
          let userArea = wx.getStorageSync('userArea') || '武汉市';
          let areaId = wx.getStorageSync('areaId') || '420100';
          that.setData({
            userArea,
            areaId
          });
          that.reLoad({ areaId })
        }
    });
  },
  goTonavigation(e) {
    wx.showLoading({
      title: '定位中...',
      icon: 'none'
    })
    let address = e.currentTarget.dataset.address;
    let title = e.currentTarget.dataset.title;
    var that = this;
    qqMap.geocoder({
      //获取表单传入地址
      address: address, //地址参数，例：固定地址，address: '北京市海淀区彩和坊路海淀西大街74号'
      success: function (res) {//成功后的回调
        console.log(res);
        var res = res.result;
        var latitude = res.location.lat;
        var longitude = res.location.lng;
        wx.getLocation({
          type: 'wgs84',
          success: function (res) {
            that.setData({
              latitude: latitude,//要去的纬度-地址
              longitude: longitude,//要去的经度-地址
            })
            wx.openLocation({//​使用微信内置地图查看位置。
              latitude: latitude,//要去的纬度-地址
              longitude: longitude,//要去的经度-地址
              name: title,
              address
            })
          },
          fail: function (error) {
            wx.hideLoading()
            wx.getSetting({
              success(res) {
                let statu = res.authSetting;
                console.log(statu['scope.userLocation'])
                if (!statu['scope.userLocation']) {
                  wx.showModal({
                    title: '是否授权当前位置',
                    content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
                    success: function (tip) {
                      if (tip.confirm) {
                        wx.openSetting({
                          success: function (data) {
                            if (data.authSetting["scope.userLocation"] === true) {
                              wx.showToast({
                                title: '授权成功',
                                icon: 'success',
                                duration: 1000
                              })
                              //授权成功之后，再调用定位进行位置获取
                              that.goTonavigation(e)
                            } else {
                              wx.showToast({
                                title: '授权失败',
                                icon: 'success',
                                duration: 1000
                              })
                            }
                          },
                        })
                      }
                    }
                  })
                }
              },
            })
          },
        })
      },
      complete: function (res) {
        console.log(res);
      }
    })
  },
  makephone(e){
    //拨打电话
    console.log(e)
    let phone = e.currentTarget.dataset.phone.split(' ')
    console.log(phone)
    if (phone.length >1){
      wx.showActionSheet({
        itemList: phone,
        success(res) {
          wx.makePhoneCall({
            phoneNumber: phone[res.tapIndex] 
          })
        },
        fail(res) {
          console.log(res.errMsg)
        }
      })
    }else{
      wx.makePhoneCall({
        phoneNumber: phone[0]
      })
    }
  },
  onUnload(){
    
  }
})